#include "ds18b20.h"
#include "wire.h"
#include "task.h"

#if DS1802_TASK

static volatile ds18b20_t ds18b20_panel;

/**
 * @brief calculate_temperature
 *
 * @param *ds18b20_param
 */
static void calculate_temperature(ds18b20_t *ds18b20_param)
{
    int16_t raw_temperature = (ds18b20_param->temp_H << 8) | ds18b20_param->temp_L;

    if ((raw_temperature & 0xf800) == 0x0000)
    {
        ds18b20_param->temp_value = (float)raw_temperature * 0.0625;
    }
}

/**
 * @brief ds18b20_read_temperature
 *
 * @param *ds18b20_param
 */
static void ds18b20_read_temperature(ds18b20_t *ds18b20_param)
{
    wire_init();           /* init wire */
    wire_write_byte(0xCC); /* jump rom */
    wire_write_byte(0x44); /* open temp exchange */
    delay_ms(50);          /* delay */
    wire_init();           /* again init wire */
    wire_write_byte(0xCC); /* jump rom */
    wire_write_byte(0xBE); /* write read cmd to ds18b20 */

    ds18b20_param->temp_L = wire_read_byte(); /* read ds18b20 L_data */
    ds18b20_param->temp_H = wire_read_byte(); /* read ds18b20 H_data */

    calculate_temperature(ds18b20_param);
}

/**
 * @brief ds18b20_struct_panel
 *
 * @return *ds18b20_panel
 */
ds18b20_t *ds18b20_struct_panel(void)
{
    return &ds18b20_panel;
}

/**
 * @brief ds18b20_proc
 *
 */
void ds18b20_proc(void)
{
    ds18b20_read_temperature(&ds18b20_panel);

#if DS18B20_DEEBUG
    printf("ds18b20 temp:%.2f", ds18b20_struct_panel()->temp_value);
#endif
}

#endif